using System.Threading;
using System.Threading.Tasks;
using Agriculture.Api.Read.Application.Command;
using Dapper;
using MediatR;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
using System.Collections.Generic; // Added for List

namespace Agriculture.Api.Read.Application.Handler
{
    /// <summary>
    /// 物流跟踪查询处理器
    /// </summary>
    public class LogisticsTrackingQueryHandler : IRequestHandler<LogisticsTrackingQuery, LogisticsTrackingResult>
    {
        private readonly IConfiguration _configuration;

        public LogisticsTrackingQueryHandler(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public async Task<LogisticsTrackingResult> Handle(LogisticsTrackingQuery request, CancellationToken cancellationToken)
        {
            string connectionString = _configuration.GetConnectionString("DefaultConnection");

            using (var connection = new MySqlConnection(connectionString))
            {
                // 查询物流基本信息
                var logisticsSql = @"
                    SELECT o.OrderNo, l.LogisticsCompany, l.TrackingNumber, 
                           o.Receiver, o.ReceiverAddress AS ReceiveAddress
                    FROM logisticstrackingmodel l
                    LEFT JOIN medicineordermodel o ON l.OrderNo = o.OrderNo
                    WHERE l.OrderNo = @OrderNo AND l.IsDeleted = 0
                    LIMIT 1";

                var logistics = await connection.QueryFirstOrDefaultAsync<LogisticsTrackingResult>(
                    logisticsSql, new { OrderNo = request.OrderNo });

                if (logistics == null)
                {
                    return null;
                }

                // 查询物流跟踪记录
                //暂时注释此段代码，等待确认正确的表名
                var trackingSql = @"
                    SELECT t.TrackingTime AS Time, t.Location, t.TrackingContent AS Detail
                    FROM logisticstrackingmodel t
                    WHERE t.TrackingNumber = @TrackingNumber AND t.IsDeleted = 0
                    ORDER BY t.TrackingTime DESC";

                var trackingItems = await connection.QueryAsync<LogisticsTrackingItem>(
                    trackingSql, new { TrackingNumber = logistics.TrackingNumber });

                logistics.TrackingItems.AddRange(trackingItems);
                

                return logistics;
            }
        }
    }
} 